import { defineStore } from "pinia";
import { ref } from "vue";
import { logoutApi, ownBuyerApi, ownSellerApi } from "../api/user";
import { delay } from "@/utils";
export const loading1 = ref(false);
export const loading2 = ref(false);
export const useUserStore = defineStore("user", {
  state: () => {
    return {
      user: "",
      id: "",
      type: -1,
      company: null,
    };
  },
  actions: {
    setUser(payload) {
      this.$state = payload;

      sessionStorage.setItem("user", JSON.stringify(payload));
    },
    removeUser() {
      this.$state = { user: "", id: "", type: -1, company: null };
      logoutApi();
      sessionStorage.removeItem("user");
    },
  },
});

export const useSellerStore = defineStore("seller", {
  state: () => {
    return {
      id: 0,
    };
  },
  actions: {
    async getSeller() {
      if (useUserStore().type === 12) {
        loading1.value = true;
        ownSellerApi().then(({ data }) => {
          if (data.length > 0) {
            const [obj] = data;
            this.$state = obj;
          }
          loading1.value = false;
        });
      }
    },
  },
});

export const useBuyerStore = defineStore("buyer", {
  state: () => {
    return { id: 0 };
  },
  actions: {
    async getBuyer() {
      if (useUserStore().type === 12) {
        loading2.value = true;
        ownBuyerApi().then(({ data }) => {
          if (data.length > 0) {
            const [obj] = data;
            this.$state = obj;
          }
          loading2.value = false;
        });
      }
    },
  },
});

export const useDetailStore = defineStore("detail", {
  state: () => {
    return {};
  },
  actions: {
    setDetail(payload) {
      console.log("payload", payload);
      this.$state = payload;
    },
  },
});
